import { Injectable } from '@nestjs/common';
import { CreateWorkpostDto } from './dto/create-workpost.dto';
import { UpdateWorkpostDto } from './dto/update-workpost.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Workpost } from './entities/workpost.entity';
import { Like, Repository } from 'typeorm';
import { StatusText } from 'src/types/enum';
import { SearchWorkPostDto } from './dto/search-workpost.dto';

@Injectable()
export class WorkpostService {

  constructor(@InjectRepository(Workpost) private workPostRepository: Repository<Workpost>) { }

  async create(createStudentDto: CreateWorkpostDto) {
    const result = await this.workPostRepository.save(createStudentDto);
    return {
      code: 200,
      msg: StatusText.CREATE_SUCCESS,
      data: result
    };
  }

  async findSearch(searchWorkPostDto: SearchWorkPostDto) {
    const search = {
      where: {},
      skip: (searchWorkPostDto.currentPage - 1) * searchWorkPostDto.pageSize,
      take: searchWorkPostDto.pageSize,
    }
    if (!searchWorkPostDto.workPostName) {
      search.where = {
        departmentId: searchWorkPostDto.departmentId,
      }
    } else {
      search.where = {
        departmentId: searchWorkPostDto.departmentId,
        workPostName: Like(`%${searchWorkPostDto.workPostName}%`)
      }
    }
    
    const result = await this.workPostRepository.find(search)
    return {
      code: 200,
      msg: StatusText.SEARCH_SUCCESS,
      data: {
        list: result
      }
    };
  }

  async findAll() {
    const result = await this.workPostRepository.find();
    return {
      code: 200,
      msg: StatusText.SEARCH_SUCCESS,
      data: {
        list: result
      }
    };
  }


  async findOne(id: number) {
    const result = await this.workPostRepository.findOne({
      where: {
        workPostId: id
      }
    })
    return {
      code: 200,
      msg: StatusText.DETAIL_SUCCESS,
      data: result
    };
  }

  async update(id: number, updateStudentDto: UpdateWorkpostDto) {
    const result = await this.workPostRepository.update(id, updateStudentDto);
    return {
      code: 200,
      msg: StatusText.UPDATE_SUCCESS,
      data: result
    };
  }

  async remove(id: number) {
    const result = await this.workPostRepository.delete({
      workPostId: id
    })
    return {
      code: 200,
      msg: StatusText.DELETE_SUCCESS,
      data: result
    };
  }
}
